package com.platform.common.utils;

import com.platform.common.config.WxPayConfig;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import com.wechat.pay.contrib.apache.httpclient.util.RsaCryptoUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import static com.wechat.pay.contrib.apache.httpclient.constant.WechatPayHttpHeaders.WECHAT_PAY_SERIAL;
import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;

public class test {
    private static final String WS_URI = "ws://192.168.10.105:8081/ws/1659496732159873025/?Authorization=f42y3drp77s6slk0i24vpbnhqcj8wfc8";
    //public static JsapiServiceExtension service;
    private static CloseableHttpClient httpClient;
    private static CertificatesManager certificatesManager;
    private static Verifier verifier;
    private static final String wechatPaySerial = "";
    public static void main( String[] args ) throws Exception {
        /*try {
            URI uri = new URI("ws://192.168.10.105:8081/ws?Authorization=f42y3drp77s6slk0i24vpbnhqcj8wfc8");
            //URI uri = new URI("ws://121.41.116.2:8089/ws?Authorization=ud8tmsn3qtvzgrp3ubfudvk8qfc47oo7");
            //URI uri = new URI("wss://121.41.116.2:8081/ws?Authorization=ud8tmsn3qtvzgrp3ubfudvk8qfc47oo7");
            //URI uri = new URI("wss://im-api.q3z3.com/ws?Authorization=ud8tmsn3qtvzgrp3ubfudvk8qfc47oo7");
            WebSocketClientInst client = new WebSocketClientInst(uri);
            // 阻塞连接
            client.connectBlocking();

            // 定时循环发送数据
            for(int i = 0 ;i < 100; i++){
                if(client.isOpen()) {
                    client.send("hello:" + i + ":" + DateUtils.getNowDate());
                }else {
                    System.out.println("webSocket client is not opened");
                }
                Thread.sleep(1000);
            }
            Thread.currentThread().join();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        /*StandardWebSocketClient client = new StandardWebSocketClient();
        WebSocketConnectionManager manager = new WebSocketConnectionManager(client, new MyHandler(), WS_URI);
        manager.start();
        Thread.sleep(100000);*/

        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(WxPayConfig.privateKeyForDecrypt);
        // 获取证书管理器实例
        certificatesManager = CertificatesManager.getInstance();
        // 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(WxPayConfig.mchid, new WechatPay2Credentials(WxPayConfig.mchid,
                        new PrivateKeySigner(WxPayConfig.mchSerialNo, merchantPrivateKey)),
                WxPayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 从证书管理器中获取verifier
        verifier = certificatesManager.getVerifier(WxPayConfig.mchid);
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(WxPayConfig.mchid, WxPayConfig.mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(certificatesManager.getVerifier(WxPayConfig.mchid)))
                .build();
        //请求URL
        /*HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi");
        // 请求body参数
        String reqdata = "{"
                + "\"amount\": {"
                + "\"total\": 100,"
                + "\"currency\": \"CNY\""
                + "},"
                + "\"mchid\": \""+WxPayConfig.mchid+"\","
                + "\"description\": \"卡费\","
                + "\"notify_url\": \""+WxPayConfig.notify_url+"\","
                + "\"payer\": {"
                + "\"openid\": \"o4GgauE1lgaPsLabrYvqhVg7O8yA\"" + "},"
                + "\"out_trade_no\": \"1217752501201407033233388881\","
                + "\"goods_tag\": \"WXG\","
                + "\"appid\": \""+WxPayConfig.appid+"\"" + "}";
        StringEntity entity = new StringEntity(reqdata,"utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
            } else if (statusCode == 204) {
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
            httpClient.close();
        }*/
        URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/transactions/id/4200000745202011093730578574");
        uriBuilder.setParameter("mchid", WxPayConfig.mchid);
        //完成签名并执行请求
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));

            } else if (statusCode == 204) {
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }
        /*PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(WxPayConfig.privateKeyForDecrypt);
        // 获取证书管理器实例
        certificatesManager = CertificatesManager.getInstance();
        // 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(WxPayConfig.mchid, new WechatPay2Credentials(WxPayConfig.mchid,
                        new PrivateKeySigner(WxPayConfig.mchSerialNo, merchantPrivateKey)),
                WxPayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 从证书管理器中获取verifier
        verifier = certificatesManager.getVerifier(WxPayConfig.mchid);
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(WxPayConfig.mchid, WxPayConfig.mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(certificatesManager.getVerifier(WxPayConfig.mchid)))
                .build();

        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/smartguide/guides");

        String text = "helloworld";
        String ciphertext = RsaCryptoUtil
                .encryptOAEP(text, verifier.getValidCertificate());

        String data = "{\n"
                + "  \"store_id\" : 1234,\n"
                + "  \"corpid\" : \"1234567890\",\n"
                + "  \"name\" : \"" + ciphertext + "\",\n"
                + "  \"mobile\" : \"" + ciphertext + "\",\n"
                + "  \"qr_code\" : \"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=xxx\",\n"
                + "  \"sub_mchid\" : \"1234567890\",\n"
                + "  \"avatar\" : \"logo\",\n"
                + "  \"userid\" : \"robert\"\n"
                + "}";
        StringEntity reqEntity = new StringEntity(data, APPLICATION_JSON);
        httpPost.setEntity(reqEntity);
        httpPost.addHeader(ACCEPT, APPLICATION_JSON.toString());
        httpPost.addHeader(WECHAT_PAY_SERIAL, wechatPaySerial);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }*/
    }
    /*public static PrepayWithRequestPaymentResponse prepayWithRequestPayment() {
        PrepayRequest request = new PrepayRequest();
        // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
        // 调用接口
        return service.prepayWithRequestPayment(request);
    }*/

    private static class MyHandler extends TextWebSocketHandler {
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            System.out.println("connected...........");
            session.sendMessage(new TextMessage("hello, web socket"));
            super.afterConnectionEstablished(session);
        }

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message)
                throws Exception {
            System.out.println("receive: " + message.getPayload());
            super.handleTextMessage(session, message);
        }
    }
}
